<?php

namespace app\hooks;

use app\api\model\ModeOrders;
use app\api\model\User;
use app\api\model\UserBalanceLog;
use app\api\model\UserGreenPointsLog;
use app\api\model\UserIntegralLog;
use think\facade\Db;
use think\helper\Str;

class MigrationHook
{
    private static $levels = [
        0 => 0,
        1 => 0,
        2 => 1,
        3 => 2,
        4 => 3,
        5 => 4,
        6 => 4,
    ];

    private static $goods_matched = [
        3164 => 1,
        3180 => 3,
        3181 => 5,
        3182 => 4,
        3186 => 2,
    ];

    public static function checkOrders()
    {

    }

    public static function syncGreens()
    {
        $users = Db::connect('shangping_mysql')->name('fa_user_property')->field(implode(', ', ['user_id', 'green']))->select()->toArray();

        foreach ($users as $k => $user) {

            $green_points = (int)((float)$user['green'] * 100);

            //判断当前用户是否存在订单
            if ($orders = ModeOrders::where('user_id', $user['user_id'])->whereIn('type', [1, 2])->where('is_delete', 0)->select()->toArray()) {

                $total_count = count($orders);

                $avg_green_points = $green_points > 0 ? ($green_points / $total_count) : 0;

                ModeOrders::whereIn('id', array_column($orders, 'id'))->update(['remain_earnings' => $avg_green_points, 'update_time' => date('Y-m-d H:i:s')]);

            }

            //计算用户结构
//            UserHook::run($user['user_id']);
            User::where('id', $user['user_id'])->update(['green_points' => $green_points, 'update_time' => date('Y-m-d H:i:s')]);


            unset($users[$k], $orders);
        }

        return true;
    }

    public static function check()
    {
        $users = [];
        $contents = [];

        foreach (User::order('id', 'asc')->column('id') as $user_id) {

            $order_green = (int)ModeOrders::where('user_id', $user_id)->where('is_delete', 0)->sum('remain_earnings');
            $user_green = (int)User::where('id', $user_id)->value('green_points');

            $surplus = (int)abs($user_green - $order_green);


            if ($surplus > 500) {

                $users[$user_id] = ["$user_green - $order_green = $surplus", ($recharge = Db::connect('shangping_mysql')->name('fa_user_green_log')->where('user_id', $user_id)->whereIn('type', ['system', 'system_out'])->sum('amount'))];

                $contents[] = "用户[ $user_id ] 剩余绿色积分 [ ".($user_green / 100)." ] 订单剩余可释放绿色积分 [ ".($order_green / 100)." ]，差额[ ".($surplus/100)." ]，累计充值[ $recharge ]";
            }

        }
        dd($users, $contents);
    }


    public static function run()
    {

//        $users = Db::connect('shangping_mysql')->name('fa_user')
//            ->order('id', 'asc')->select()->toArray();
//
//        foreach ($users as $uk => $user) {
////
////            if (User::where('id', $user['id'])->count() <= 0) {
//
//                $property = Db::connect('shangping_mysql')->name('fa_user_property')->where('user_id', $user['id'])->findOrEmpty();
//
//                User::where('id', $user['id'])->update($user_info = [
//                    'green_points' => (int)((float)$property['green'] * 100),
//                    'balance' => (int)((float)$property['balance'] * 100),
//                    'integral' => (int)((float)$property['score'] * 100),
//                    'invest_balance' => 0,
//                    'invest_count' => 0,
//                    'welfare_points' => 0,
//                    'mode_one_level_id' => self::$levels[(int)$user['grade']],
//                    'mode_three_level_id' => 0,
//                    'mode_one_real_level_id' => self::$levels[(int)$user['grade']],
//                    'mode_three_real_level_id' => 0,
//                    'padian_rate' => 0,
//                    'update_time' => date('Y-m-d H:i:s', (int)$user['updatetime'] ?: time()),
//                ]);
////
////                $user_info = [
////                    'id' => (int)$user['id'],
////                    'parent_ids' => '',
////                    'pid' => (int)$user['parent_user_id'],
////                    'green_points' => (int)((float)$property['green'] * 100),
////                    'balance' => (int)((float)$property['balance'] * 100),
////                    'integral' => (int)((float)$property['score'] * 100),
////                    'invest_balance' => 0,
////                    'invest_count' => 0,
////                    'welfare_points' => 0,
////                    'mode_one_level_id' => self::$levels[(int)$user['grade']],
////                    'mode_three_level_id' => 0,
////                    'mode_one_real_level_id' => self::$levels[(int)$user['grade']],
////                    'mode_three_real_level_id' => 0,
////                    'padian_rate' => 0,
////                    'union_id' => 0,
////                    'limit_withdraw' => 0,
////                    'limit_goumai_money' => 0,
////                    'limit_benefit' => 'off',
////                    'alipay' => '',
////                    'alipay_name' => '',
////                    'alipay_status' => 1,
////                    'bid' => 0,
////                    'level_id' => 0,
////                    'levelup_time' => date('Y-m-d H:i:s'),
////                    'nickname' => $user['nickname'],
////                    'birthday' => $user['birthday'],
////                    'avatar' => 'https://static.shangping.cc'.$user['avatar'],
////                    'sex' => 'off',
////                    'remark' => '',
////                    'phone' => $user['mobile'],
////                    'mail' => NULL,
////                    'password' => '',
////                    'pay_password' => '',
////                    'type' => 1,
////                    'invite_code' => User::uniqueInviteCode(),
////                    'create_time' => date('Y-m-d H:i:s', (int)$user['createtime'] ?: time()),
////                    'update_time' => date('Y-m-d H:i:s', (int)$user['updatetime'] ?: time()),
////                ];
////
////                User::create($user_info);
//
//                if ($user_info['green_points'] > 0) {
//
//                    UserGreenPointsLog::create([
//                        'user_id' => $user['id'],
//                        'amount' => $user_info['green_points'],
//                        'type' => 'init',
//                        'content' => '旧众益健康迁移同步初始化',
//                        'before' => $user_info['green_points'],
//                        'create_time' => date('Y-m-d H:i:s')
//                    ]);
//
//                }
//
//                if ($user_info['balance'] > 0) {
//
//                    UserBalanceLog::create([
//                        'user_id' => $user['id'],
//                        'amount' => $user_info['balance'],
//                        'type' => 'init',
//                        'content' => '旧众益健康迁移同步初始化',
//                        'before' => $user_info['balance'],
//                        'create_time' => date('Y-m-d H:i:s')
//                    ]);
//
//                }
//
//                if ($user_info['integral'] > 0) {
//
//                    UserIntegralLog::create([
//                        'user_id' => $user['id'],
//                        'amount' => $user_info['integral'],
//                        'type' => 'init',
//                        'content' => '旧众益健康迁移同步初始化',
//                        'before' => $user_info['integral'],
//                        'create_time' => date('Y-m-d H:i:s')
//                    ]);
//
//                }
//
////            }
//
//            unset($users[$uk]);
//        }

        //查询全部等待释放订单信息
        $reback_orders = Db::connect('shangping_mysql')->name('fa_shopro_order_reback')->order('id', 'asc')->select()->toArray();

        foreach ($reback_orders as $rk => $reback_order) {

            //判断是否存在
            if (Db::connect('shangping_mysql')->name('fa_user_green_log')->where('type', 'free_refund')->where('item_id', (int)$reback_order['order_id'])->count()) {

                continue;

            }

            $mode_order = [
                'order_sn' => 'MODE-A-'.date('YmdHis', $reback_order['create_time']).'-'.$reback_order['order_id'],
                'user_id' => (int)$reback_order['user_id'],
                'product_id' => self::$goods_matched[(int)$reback_order['goods_id']],
                'num' => $reback_order['goods_num'],
                'status' => 'payed',
                'pay_amount' => (int)((float)$reback_order['goods_price'] * (int)$reback_order['goods_num'] * 100),
                'pay_real' => (int)((float)$reback_order['pay'] * 100),
                'pay_type' => 'other',
                'type' => (int)$reback_order['goods_price'] === 298 ? 2 : 1,
                'achievements' => '',
                'active_achievements' => '',
                'last_achievements_time' => 0,
                'principal' => (int)((float)$reback_order['pay'] * 100),
                'earnings' => (int)((float)$reback_order['score_total'] * 100),
//                'remain_earnings' => (int)((float)$reback_order['score_last'] * 100),
                'remain_earnings' => (int)((float)$reback_order['score_total'] * 100),
                'pay_resp' => '',
                'create_time' => date('Y-m-d H:i:s', $reback_order['create_time']),
                'pay_time' => date('Y-m-d H:i:s', $reback_order['create_time']),
                'update_time' => date('Y-m-d H:i:s'),
                'order_status' => 0,
                'is_delete' => 0
            ];

            if (ModeOrders::where('order_sn', $mode_order['order_sn'])->count() <= 0) {

                ModeOrders::create($mode_order);

            }

            unset($reback_orders[$rk]);
        }

        foreach (Db::connect('shangping_mysql')->name('fa_user')->order('id', 'desc')->select()->toArray() as $user) {

            //查询当前用户已释放总积分
            $release_green_amount = (int)abs((float)Db::connect('shangping_mysql')->name('fa_user_green_log')->whereNotIn('type', ['system', 'system_out'])->where('user_id', $user['id'])->where('amount', '<', 0)->sum('amount') * 100);

            //查询所有订单
            if ($release_green_amount > 0 && $orders = ModeOrders::where('user_id', $user['id'])->order('id', 'asc')->select()) {
                //获取所有订单
                $orders = $orders->toArray();

                //循环所有订单
                foreach ($orders as $k => $order) {

                    //获取扣除
                    $last_earnings = (int)$order['earnings'] - ($deduct_earnings = (int)min((int)$order['earnings'], $release_green_amount));

                    //设置订单剩余可释放
                    ModeOrders::where('id', $order['id'])->update(['remain_earnings' => $last_earnings,  'update_time' => date('Y-m-d H:i:s')]);

                    $release_green_amount -= $deduct_earnings;

                    //判断释放金额
                    if ($release_green_amount <= 0) {

                        break;

                    }
                    unset($orders[$k]);
                }
            }



            User::where('id', $user['id'])->update([
                'mode_one_spending' => ModeOrders::where('user_id', $user['id'])->whereIn('type', [1, 2])->where('status', 'payed')->sum('pay_amount'),
                'update_time' => date('Y-m-d H:i:s'),
            ]);

//            UserHook::run($user['id']);

        }

        return true;

    }

    public static function sync()
    {
        $users = Db::connect('mysql')->table('yc_app_user_copy2')->where('id', '>', 80000)->order('id', 'asc')->select()->toArray();
        foreach ($users as $user) {

            $user_info = [
                'id' => (int)$user['id'],
                'parent_ids' => '',
                'pid' => (int)$user['pid'],
                'green_points' => 0,
                'balance' => 0,
                'integral' => 0,
                'invest_balance' => 0,
                'invest_count' => 0,
                'welfare_points' => 0,
                'mode_one_level_id' => 0,
                'mode_three_level_id' => 0,
                'mode_one_real_level_id' => 0,
                'mode_three_real_level_id' => 0,
                'padian_rate' => 0,
                'union_id' => 0,
                'limit_withdraw' => 0,
                'limit_goumai_money' => 0,
                'limit_benefit' => 'off',
                'alipay' => '',
                'alipay_name' => '',
                'alipay_status' => 1,
                'bid' => 0,
                'level_id' => 0,
                'levelup_time' => date('Y-m-d H:i:s'),
                'nickname' => $user['nickname'],
                'birthday' => $user['birthday'],
                'avatar' => $user['avatar'],
                'sex' => 'off',
                'remark' => '',
                'phone' => in_array($user['phone'], ['13029965607', '13118173939', '15604535025']) ? ($user['phone'].'_01') : $user['phone'],
                'mail' => NULL,
                'password' => '',
                'pay_password' => '',
                'type' => 1,
                'invite_code' => $user['invite_code'],
                'create_time' => $user['create_time'],
                'update_time' => $user['update_time'],
            ];

            User::create($user_info);

            UserHook::run($user_info['id']);


        }
    }


    public static function greenPolish()
    {
        $lists = [
            50002 => 9999.87,
            50003 => -1069.6,
            50013 => 76730.2,
            50017 => 75551.55,
            50020 => 227741.56,
            50021 => 4223.3,
            50022 => 43344.5,
            50033 => 1608.41,
            50050 => -535.2,
            50054 => 277352.79,
            50061 => 2064.36,
            50067 => 241226,
            50069 => 96133.53,
            50070 => 35860.14,
            50072 => 34992,
            50074 => 100988.25,
            50075 => 203832.4,
            50078 => 0.4,
            50097 => -5000,
            50128 => 8320,
            50136 => 536.4,
            50137 => 115862.4,
            50138 => 114790,
            50147 => 71877.6,
            50221 => 15000,
            50320 => 109999.99,
            50389 => 30000,
            50404 => 22000,
            50463 => 39352,
            50512 => 20000,
            50600 => 125000,
            50643 => 43040
        ];
        foreach ($lists as $user_id => $amount) {

            $amount = (int)($amount * 100);

            $order =  ModeOrders::where('user_id', $user_id)->where('is_delete', 0)->whereIn('type', [1, 2])->where('status', 'payed')->order('remain_earnings', 'desc')->order('principal', 'desc')->findOrEmpty()->toArray();


            if ($amount > 0) {
                //设置信息
                ModeOrders::where('id', $order['id'])->inc('remain_earnings', $amount)->update();

            } else {

                //设置信息
                ModeOrders::where('id', $order['id'])->dec('remain_earnings', (int)abs($amount))->update();
            }

            User::where('id', $user_id)->update([
                'green_points' => ModeOrders::where('user_id', $user_id)->where('is_delete', 0)->whereIn('type', [1, 2])->where('status', 'payed')->whereNotNull('pay_time')->where('remain_earnings', '>', 0)->sum('remain_earnings'),
                'update_time' => date('Y-m-d H:i:s')
            ]);

        }

        return true;
    }


    public static function modeThreeWrong()
    {
        $order_ids = ModeOrders::where('type', 4)->where('is_delete', 0)->where('status', 'payed')->column('id');
        //整理信息
        $lists = [];
        foreach ($order_ids as $order_id) {
            if ($integral = UserIntegralLog::where('type', 'speedup')->whereLike('content', '['.$order_id.']加速收益%')->select()) {
                $integral = $integral->toArray();
                foreach ($integral as $item) {
                    if (Str::startsWith($item['content'], ('['.$order_id.']加速收益-级差')) || Str::startsWith($item['content'], ('['.$order_id.']加速收益-平级'))) {
                        if (!isset($lists[$item['user_id']])) {
                            $lists[$item['user_id']] = ['integral' => 0, 'balance' => 0];
                        }
                        $lists[$item['user_id']]['integral'] += $item['amount'];
                    }
                }
            }
            if ($balance = UserBalanceLog::where('type', 'speedup')->whereLike('content', '['.$order_id.']加速收益%')->select()) {
                $balance = $balance->toArray();
                foreach ($balance as $item) {
                    if (Str::startsWith($item['content'], ('['.$order_id.']加速收益-级差')) || Str::startsWith($item['content'], ('['.$order_id.']加速收益-平级'))) {
                        if (!isset($lists[$item['user_id']])) {
                            $lists[$item['user_id']] = ['integral' => 0, 'balance' => 0];
                        }
                        $lists[$item['user_id']]['balance'] += $item['amount'];
                    }
                }
            }
        }
        $contents = [];
        foreach ($lists as $user_id => $list) {

            $contents[] = '用户 ['.$user_id.'] 需扣除余额 '.($list['balance'] / 100).' ; 消费积分：'.($list['integral'] / 100);

        }

        dd($contents);
    }


}